package com.sanjiahantang.youjiaclient.module.decorate.views.impl;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.TextureView;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.google.zxing.common.StringUtils;
import com.sanjiahantang.plugin.pickerview.OptionsPickerView;
import com.sanjiahantang.plugin.pickerview.TimePickerView;
import com.sanjiahantang.uilibrary.utils.Utils;
import com.sanjiahantang.youjiaclient.R;
import com.sanjiahantang.youjiaclient.base.BaseMvpActivity;
import com.sanjiahantang.youjiaclient.base.BaseView;
import com.sanjiahantang.youjiaclient.config.ConfigValue;
import com.sanjiahantang.youjiaclient.module.common.beans.ConditionBean;
import com.sanjiahantang.youjiaclient.module.login.views.impl.LoginActivity;
import com.sanjiahantang.youjiaclient.module.common.views.impl.SelectorActivity;
import com.sanjiahantang.youjiaclient.module.decorate.beans.DecorateDicBean;
import com.sanjiahantang.youjiaclient.module.decorate.presenters.DecorateManagePresenter;
import com.sanjiahantang.youjiaclient.module.decorate.views.DecorateManageView;
import com.sanjiahantang.youjiaclient.module.store.views.impl.StoreActivity;
import com.sanjiahantang.youjiaclient.utils.CheckUtil;
import com.sanjiahantang.youjiaclient.utils.FileUtils;
import com.sanjiahantang.youjiaclient.utils.IdCardValidator;
import com.squareup.picasso.Picasso;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

import static com.sanjiahantang.youjiaclient.config.StaticValue.KEY_PARAM;
import static com.sanjiahantang.youjiaclient.config.StaticValue.KEY_TITLE;
import static com.sanjiahantang.youjiaclient.module.common.views.SelectorView.KEY_INDEX;

/**
 * Created by admin on 2017/8/7.
 */

public class DecorateFormActivity extends BaseMvpActivity<DecorateManageView, DecorateManagePresenter> implements DecorateManageView, View.OnClickListener {

    private View llTop, rl_decorate_designer;
    private TextView btnNearShop;


    private TextView title, txtJob, txtDoor, txtStyle, txtPrice, txtCreateTime, txtCity, txtPreTime, txtDesignerName, txtIdCard;
    private EditText txtName, txtAddress, txtArea;
    private ArrayList<ConditionBean.SelectorData> jobList, doorList, styleList, priceList;
    private ConditionBean.SelectorData jobData, doorData, styleData, priceData;
    private OptionsPickerView pvOptions;
    private TimePickerView pvTime;

    private ArrayList<String> listProvince;
    private ArrayList<ArrayList<String>> listCity;
    private ArrayList<ArrayList<ArrayList<String>>> listArea;

    private RadioButton rb_man, rb_baby_yes, rb_old_yes;
    private RadioGroup rgGender, rgBaby, rgOld;
    private DecorateDicBean.Data mData;
    private ImageView ivDesignerPhoto;

    @Override
    public DecorateManagePresenter initPresenter() {
        return new DecorateManagePresenter();
    }

    @Override
    public void initView() {
        setContentView(R.layout.activity_decorate);
        llTop = findViewById(R.id.ll_decorate_top);
        rl_decorate_designer = findViewById(R.id.rl_decorate_designer);
        btnNearShop = (TextView) findViewById(R.id.btn_decorate_nearshop);
        findViewById(R.id.fl_Back).setOnClickListener(this);
        findViewById(R.id.vIdCard).setVisibility(View.GONE);

        btnNearShop.setVisibility(View.VISIBLE);
        btnNearShop.setOnClickListener(this);
        ivDesignerPhoto = (ImageView) findViewById(R.id.ivDesignerPhoto);

        txtJob = (TextView) findViewById(R.id.txtJob);
        txtDoor = (TextView) findViewById(R.id.txtDoor);
        txtStyle = (TextView) findViewById(R.id.txtStyle);
        txtPrice = (TextView) findViewById(R.id.txtPrice);
        txtCreateTime = (TextView) findViewById(R.id.txtCreateTime);
        txtCity = (TextView) findViewById(R.id.txtCity);
        txtPreTime = (TextView) findViewById(R.id.txtPreTime);
        txtIdCard = (TextView) findViewById(R.id.txtIdCard);

        txtName = (EditText) findViewById(R.id.txtName);
        txtAddress = (EditText) findViewById(R.id.txtAddress);
        txtArea = (EditText) findViewById(R.id.txtArea);
        txtDesignerName = (TextView) findViewById(R.id.txtDesignerName);

        rb_man = (RadioButton) findViewById(R.id.rb_man);
        rb_baby_yes = (RadioButton) findViewById(R.id.rb_baby_yes);
        rb_old_yes = (RadioButton) findViewById(R.id.rb_old_yes);

        findViewById(R.id.vJob).setOnClickListener(this);
        findViewById(R.id.vDoor).setOnClickListener(this);
        findViewById(R.id.vStyle).setOnClickListener(this);
        findViewById(R.id.vPrice).setOnClickListener(this);
        findViewById(R.id.vCity).setOnClickListener(this);
        findViewById(R.id.vPreTime).setOnClickListener(this);
        findViewById(R.id.btnDill).setOnClickListener(this);

        rgGender = (RadioGroup) findViewById(R.id.rgGender);
        rgBaby = (RadioGroup) findViewById(R.id.rgBaby);
        rgOld = (RadioGroup) findViewById(R.id.rgOld);

        presenter.setOnLoadListener(new OnLoadListener() {
            @Override
            public void loadData(DecorateDicBean.Data data) {
                mData = data;
                View llDesignerName = findViewById(R.id.llDesignerName);
                jobList = (ArrayList<ConditionBean.SelectorData>) data.getDutyList();
                doorList = (ArrayList<ConditionBean.SelectorData>) data.getDoorList();
                styleList = (ArrayList<ConditionBean.SelectorData>) data.getStyleList();
                priceList = (ArrayList<ConditionBean.SelectorData>) data.getBudgetList();


                if (data.getSex() == 0) {
                    rgGender.check(R.id.rb_man);
                } else {
                    rgGender.check(R.id.rb_woman);
                }

                if (data.getIdCode() != null) {
                    txtIdCard.setText(data.getIdCode());
                }

                if (!TextUtils.isEmpty(data.getJobCode())) {
                    jobData = new ConditionBean.SelectorData();
                    jobData.setDicValue(data.getJobCode());
                    jobData.setDicName(data.getJobName());
                    txtJob.setText(data.getJobName());
                }
                if (data.getUserName() != null) {
                    txtName.setText(data.getUserName());
                }
                if (data.getAddress() != null) {
                    txtCity.setText(data.getAddress());
                }
                if (data.getApartmentName() != null) {
                    txtAddress.setText(data.getApartmentName());
                }

                if (data.getIsHaveBaby() == 0) {
                    rgBaby.check(R.id.rb_baby_no);
                } else {
                    rgBaby.check(R.id.rb_baby_yes);
                }

                if (data.getHasTogether() == 0) {
                    rgOld.check(R.id.rb_old_no);
                } else {
                    rgOld.check(R.id.rb_old_yes);
                }

                if (!TextUtils.isEmpty(data.getApartmentTypeCode())) {
                    doorData = new ConditionBean.SelectorData();
                    doorData.setDicValue(data.getApartmentTypeCode());
                    doorData.setDicName(data.getApartmentTypeName());
                    txtDoor.setText(data.getApartmentTypeName());
                }

                if (!TextUtils.isEmpty(data.getLikeStyleCode())) {
                    styleData = new ConditionBean.SelectorData();
                    styleData.setDicValue(data.getLikeStyleCode());
                    styleData.setDicName(data.getLikeStyleName());
                    txtStyle.setText(data.getLikeStyleName());
                }

                if (data.getApartmentArea() != null) {
                    txtArea.setText(data.getApartmentArea());
                }

                if (!TextUtils.isEmpty(data.getBudgetCode())) {
                    priceData = new ConditionBean.SelectorData();
                    priceData.setDicValue(data.getBudgetCode());
                    priceData.setDicName(data.getBudgetName());
                    txtPrice.setText(data.getBudgetName());
                }

                txtPreTime.setText(Utils.getStandardFormat(data.getPlanDecorateTime()));
                txtCreateTime.setText(Utils.getStandardFormat(data.getFinishDate()));
                rl_decorate_designer.setVisibility(View.VISIBLE);

                if (data.getDesignList() != null) {
                    llTop.setVisibility(View.VISIBLE);
                    if (!TextUtils.isEmpty(data.getDesignList().getUserName())) {

                        llDesignerName.setVisibility(View.VISIBLE);
                    } else {
                        llDesignerName.setVisibility(View.GONE);
                    }
                    txtDesignerName.setText(data.getDesignList().getUserName() == null ? "" : data.getDesignList().getUserName());
                    Picasso.with($this).load(FileUtils.rePath(data.getDesignList().getUrl())).into(ivDesignerPhoto);
                } else {
                    llTop.setVisibility(View.VISIBLE);
                    llDesignerName.setVisibility(View.GONE);
                }

            }
        });

        init();
    }

    private void init() {

        presenter.loadCityList($this, new BaseView.OnLoadListener() {
            @Override
            public void onLoad(Object content) {
                Object[] listArray = (Object[]) content;
                listProvince = (ArrayList<String>) listArray[0];
                listCity = (ArrayList<ArrayList<String>>) listArray[1];
                listArea = (ArrayList<ArrayList<ArrayList<String>>>) listArray[2];
                pvOptions = new OptionsPickerView.Builder($this, new OptionsPickerView.OnOptionsSelectListener() {
                    @Override
                    public void onOptionsSelect(int options1, int options2, int options3, View v) {
                        //返回的分别是三个级别的选中位置
                        String tx = listProvince.get(options1) + " " +
                                listCity.get(options1).get(options2) + " " +
                                listArea.get(options1).get(options2).get(options3);
                        txtCity.setText(tx);
                        //    presenter.setData(context,txtUserName.getText().toString(),"",txtJob.getText().toString(),txtLocation.getText().toString(),txtInterest.getText().toString(),"address","");

                    }
                })

                        .setTitleText("")
                        .setDividerColor(Color.BLACK)
                        .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                        .setContentTextSize(20)
                        .build();

        /*pvOptions.setPicker(options1Items);//一级选择器
        pvOptions.setPicker(options1Items, options2Items);//二级选择器*/
                pvOptions.setPicker(listProvince, listCity, listArea);//三级选择器
            }
        });

        //控制时间范围(如果不设置范围，则使用默认时间1900-2100年，此段代码可注释)
        //因为系统Calendar的月份是从0-11的,所以如果是调用Calendar的set方法来设置时间,月份的范围也要是从0-11
        Calendar selectedDate = Calendar.getInstance();
        Calendar startDate = Calendar.getInstance();
        startDate.set(selectedDate.get(Calendar.YEAR), selectedDate.get(Calendar.MONTH), selectedDate.get(Calendar.DAY_OF_MONTH));
        Calendar endDate = Calendar.getInstance();
        endDate.set(selectedDate.get(Calendar.YEAR) + 100, selectedDate.get(Calendar.MONTH), selectedDate.get(Calendar.DAY_OF_MONTH));
        //时间选择器
        pvTime = new TimePickerView.Builder($this, new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
                // 这里回调过来的v,就是show()方法里面所添加的 View 参数，如果show的时候没有添加参数，v则为null
                /*btn_Time.setText(getTime(date));*/
                txtPreTime.setText(getTime(date));
            }
        })
                //年月日时分秒 的显示与否，不设置则默认全部显示
                .setType(new boolean[]{true, true, false, false, false, false})
                .setLabel("", "", "", "", "", "")
                .isCenterLabel(false)
                .setDividerColor(Color.DKGRAY)
                .setContentSize(21)
                .setDate(selectedDate)
                .setRangDate(startDate, endDate)
                .setBackgroundId(0x00FFFFFF) //设置外部遮罩颜色
                .setDecorView(null)
                .build();
    }

    private String getTime(Date date) {//可根据需要自行截取数据显示
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM");
        return format.format(date);
    }

    @Override
    public void initData() {
        if (TextUtils.isEmpty(ConfigValue.DATA_KEY)) {
            LoginActivity.logout($this);
            finish();
            return;
        } else {
            presenter.indexDecorateInfoForCustomer($this);
        }

    }

    @Override
    public void showProgress() {
        super.showProgress($this);
    }


    @Override
    public DecorateManagePresenter getPresenter() {
        return presenter;
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.fl_Back:
                finish();
                break;
            case R.id.vJob:
                if (jobList != null) {
                    Intent intent = new Intent($this, SelectorActivity.class);
                    Bundle b = new Bundle();
                    b.putSerializable(KEY_PARAM, jobList);
                    intent.putExtra(KEY_PARAM, b);
                    intent.putExtra(KEY_TITLE, "选择职业");
                    if (jobData != null)
                        intent.putExtra(KEY_INDEX, jobData.getDicValue());
                    startActivityForResult(intent, INTENT_JOB);
                }
                break;
            case R.id.vDoor:
                if (doorList != null) {
                    Intent intent = new Intent($this, SelectorActivity.class);
                    Bundle b = new Bundle();
                    b.putSerializable(KEY_PARAM, doorList);
                    intent.putExtra(KEY_PARAM, b);
                    intent.putExtra(KEY_TITLE, "选择户型");
                    if (doorData != null)
                        intent.putExtra(KEY_INDEX, doorData.getDicValue());
                    startActivityForResult(intent, INTENT_DOOR);
                }
                break;
            case R.id.vStyle:
                if (styleList != null) {
                    Intent intent = new Intent($this, SelectorActivity.class);
                    Bundle b = new Bundle();
                    b.putSerializable(KEY_PARAM, styleList);
                    intent.putExtra(KEY_PARAM, b);
                    intent.putExtra(KEY_TITLE, "选择风格");
                    if (styleData != null)
                        intent.putExtra(KEY_INDEX, styleData.getDicValue());
                    startActivityForResult(intent, INTENT_STYLE);
                }
                break;
            case R.id.vPrice:
                if (priceList != null) {
                    Intent intent = new Intent($this, SelectorActivity.class);
                    Bundle b = new Bundle();
                    b.putSerializable(KEY_PARAM, priceList);
                    intent.putExtra(KEY_TITLE, "选择预算");
                    intent.putExtra(KEY_PARAM, b);
                    if (priceData != null)
                        intent.putExtra(KEY_INDEX, priceData.getDicValue());
                    startActivityForResult(intent, INTENT_PRICE);
                }
                break;
            case R.id.vCity:
                pvOptions.show();
                break;
            case R.id.vPreTime:
                pvTime.show();
                break;
            case R.id.btnDill:
                checkSubmit();
                break;
            case R.id.btn_decorate_nearshop:
                Intent intent = new Intent($this, StoreActivity.class);
                startActivity(intent);
                finish();
                break;
        }
    }

    private void checkSubmit() {
        if (mData == null) {
            return;
        }
        if (TextUtils.isEmpty(txtName.getText())) {
            Utils.showToast($this, "请填写姓名");
            return;
        }

        if (CheckUtil.isChinese(txtName.getText().toString())) {
            Utils.showToast($this, "请填写中文姓名");
            return;
        }

        if (txtName.getText().toString().length() < 2 || txtName.getText().toString().length() > 4){
            Utils.showToast($this, "输入的姓名过长或过短");
            return;
        }

        if (TextUtils.isEmpty(txtIdCard.getText())) {
            Utils.showToast($this, "请填写身份证号");
            return;
        }

        if (!IdCardValidator.isValidatedAllIdcard(txtIdCard.getText().toString())) {
            Utils.showToast($this, "请填写正确的身份证号");
            return;
        }


        if (jobData == null) {
            Utils.showToast($this, "请选择职业");
            return;
        }

        if (TextUtils.isEmpty(txtCity.getText())) {
            Utils.showToast($this, "请选择楼盘地址");
            return;
        }

        if (TextUtils.isEmpty(txtAddress.getText())) {
            Utils.showToast($this, "请填写您的小区名称");
            return;
        }

        if (CheckUtil.isEmoji(txtAddress.getText().toString())) {
            Utils.showToast($this, "请正确填写您的小区名称");
            return;
        }

        if (doorData == null) {
            Utils.showToast($this, "请选择户型");
            return;
        }

        if (styleData == null) {
            Utils.showToast($this, "请选择您喜欢的风格");
            return;
        }

        if (TextUtils.isEmpty(txtArea.getText())) {
            Utils.showToast($this, "请填写面积");
            return;
        }

        if (priceData == null) {
            Utils.showToast($this, "请选择您的预算范围");
            return;
        }

        if (TextUtils.isEmpty(txtPreTime.getText())) {
            Utils.showToast($this, "请选择您的预计装修时间");
            return;
        }
        String from = this.getIntent().getStringExtra(KEY_FROM);
        String experienceName = this.getIntent().getStringExtra(KEY_EXPERIENCENAME);
        String experiencePhone = this.getIntent().getStringExtra(KEY_EXPERIENCEPHONE);
        if (from != null && (TextUtils.isEmpty(experienceName) || TextUtils.isEmpty(experiencePhone))) {
            return;
        }

        presenter.saveUserRequireInfoForCustomer(
                $this,
                txtName.getText().toString().replaceAll("\n"," "),
                "513321197404260515",
                rb_man.isChecked() ? 0 : 1,
                jobData,
                txtCity.getText().toString(),
                txtAddress.getText().toString().replaceAll("\n"," "),
                rb_baby_yes.isChecked() ? 1 : 0,
                rb_old_yes.isChecked() ? 1 : 0,
                doorData,
                styleData,
                txtArea.getText().toString().trim(),
                priceData,
                txtPreTime.getText().toString(),
                mData.getDesignStateId(),
                mData.getProjectStateId(),
                mData.getSupervisionStateId(),
                mData.getTotalStateId(),
                mData.getId(), experienceName, experiencePhone
        );
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case INTENT_JOB:
                    jobData = (ConditionBean.SelectorData) data.getSerializableExtra(KEY_PARAM);
                    if (jobData != null) {
                        txtJob.setText(jobData.getDicName());
                    }
                    break;
                case INTENT_DOOR:
                    doorData = (ConditionBean.SelectorData) data.getSerializableExtra(KEY_PARAM);
                    if (doorData != null) {
                        txtDoor.setText(doorData.getDicName());
                    }
                    break;
                case INTENT_STYLE:
                    styleData = (ConditionBean.SelectorData) data.getSerializableExtra(KEY_PARAM);
                    if (styleData != null) {
                        txtStyle.setText(styleData.getDicName());
                    }
                    break;
                case INTENT_PRICE:
                    priceData = (ConditionBean.SelectorData) data.getSerializableExtra(KEY_PARAM);
                    if (priceData != null) {
                        txtPrice.setText(priceData.getDicName());
                    }
                    break;
            }
        }
    }
}
